package com.weixin.mp.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Slf4j
@Component
public class JwtUtils {
    
    @Value("${jwt.secret}")
    private String secret;
    
    @Value("${jwt.expire}")
    private long expire;
    
    @Value("${jwt.header}")
    private String header;
    
    private static String staticSecret;
    private static long staticExpire;
    private static String staticHeader;
    
    @PostConstruct
    public void init() {
        staticSecret = secret;
        staticExpire = expire;
        staticHeader = header;
        log.info("JWT工具类初始化完成，header: {}, expire: {}", header, expire);
    }
    
    /**
     * 生成token
     */
    public static String generateToken(Long userId, String openid) {
        log.info("生成token，userId: {}, openid: {}", userId, openid);
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + staticExpire * 1000);
        
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("openid", openid);
        
        String token = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, staticSecret)
                .compact();
        
        log.info("生成token成功: {}", token);
        return token;
    }
    
    /**
     * 解析token
     */
    public static Claims getClaimsByToken(String token) {
        try {
            log.info("解析token: {}", token);
            Claims claims = Jwts.parser()
                    .setSigningKey(staticSecret)
                    .parseClaimsJws(token)
                    .getBody();
            log.info("解析token成功, claims: {}", claims);
            return claims;
        } catch (Exception e) {
            log.error("解析token失败", e);
            return null;
        }
    }
    
    /**
     * 判断token是否过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
    
    /**
     * 从token中获取用户ID
     */
    public static Long getUserIdFromToken(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        Claims claims = getClaimsByToken(token);
        if (claims == null) {
            return null;
        }
        return claims.get("userId", Long.class);
    }
    
    /**
     * 从token中获取openid
     */
    public static String getOpenidFromToken(String token) {
        if (token == null || token.isEmpty()) {
            log.warn("尝试从空token获取openid");
            return null;
        }
        Claims claims = getClaimsByToken(token);
        if (claims == null) {
            log.warn("从token解析claims失败: {}", token);
            return null;
        }
        return claims.get("openid", String.class);
    }
    
    /**
     * 获取JWT的header名称
     */
    public static String getHeader() {
        return staticHeader;
    }
} 